package com.ruoyi.draw.controller;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.draw.config.ServerConfigs;
import com.ruoyi.draw.domain.ModelConfig;
import com.ruoyi.draw.domain.PromptConfig;
import com.ruoyi.draw.domain.bo.ImageCreate;
import com.ruoyi.draw.domain.bo.NovelCreate;
import com.ruoyi.draw.domain.bo.RoleCreate;
import com.ruoyi.draw.domain.bo.StoryBoardCreate;
import com.ruoyi.draw.domain.bo.ImageCreate;
import com.ruoyi.draw.service.IModelConfigService;
import com.ruoyi.draw.service.IPromptConfigService;
import com.ruoyi.draw.util.IMGuse;

import com.ruoyi.draw.util.LLMuse;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 小说封面生成接口
 * 调用LLM优化提示词 + 图像API生成封面
 */
@RestController
@RequestMapping("API/gen/")
public class APIGenController extends BaseController {

    @Autowired private IModelConfigService modelConfigService;
    @Autowired private IPromptConfigService promptConfigService;
    @Autowired private LLMuse llmUse;
    @Autowired private IMGuse imgUse;


    @PostMapping("/optimize-prompt")
    public ResponseEntity<Map<String, Object>> optimizePrompt(@RequestBody NovelCreate novelCreate) {
        Map<String, Object> result = new HashMap<>();

        try {
            ModelConfig textModelConfig = modelConfigService.selectModelConfigById(novelCreate.getText_model_id());
            PromptConfig promptConfig = promptConfigService.selectPromptConfigById(novelCreate.getPrompt_id());

            // 调用 LLM 优化封面提示词
            String optimizedPrompt = llmUse.optimizeCoverPrompt(textModelConfig, promptConfig, novelCreate);

            result.put("success", true);
            result.put("optimizedPrompt", optimizedPrompt);

        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "优化异常：" + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }

    @PostMapping("/optimize-role-prompt")
    public ResponseEntity<Map<String, Object>> optimizePrompt(@RequestBody RoleCreate roleCreate) {
        Map<String, Object> result = new HashMap<>();

        try {
            ModelConfig textModelConfig = modelConfigService.selectModelConfigById(roleCreate.getText_model_id());
            PromptConfig promptConfig = promptConfigService.selectPromptConfigById(roleCreate.getPrompt_id());

            // 调用 LLM 优化封面提示词
            String optimizedPrompt = llmUse.optimizeRolePrompt(textModelConfig, promptConfig, roleCreate);

            result.put("success", true);
            result.put("optimizedPrompt", optimizedPrompt);

        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "优化异常：" + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }


    @PostMapping("/optimize-story-prompt")
    public ResponseEntity<Map<String, Object>> optimizePrompt(@RequestBody StoryBoardCreate storyBoardCreateCreate) {
        Map<String, Object> result = new HashMap<>();

        try {
            ModelConfig textModelConfig = modelConfigService.selectModelConfigById(storyBoardCreateCreate.getText_model_id());
            PromptConfig promptConfig = promptConfigService.selectPromptConfigById(storyBoardCreateCreate.getPrompt_id());

            // 调用 LLM 优化封面提示词
            String optimizedPrompt = llmUse.optimizeStoryBoardPrompt(textModelConfig, promptConfig, storyBoardCreateCreate);

            result.put("success", true);
            result.put("optimizedPrompt", optimizedPrompt);

        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "优化异常：" + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }

    @PostMapping("/optimize-storyimg-prompt")
    public ResponseEntity<Map<String, Object>> optimizePrompts(@RequestBody StoryBoardCreate storyBoardCreateCreate) {
        Map<String, Object> result = new HashMap<>();

        try {
            ModelConfig textModelConfig = modelConfigService.selectModelConfigById(storyBoardCreateCreate.getText_model_id());
            PromptConfig promptConfig = promptConfigService.selectPromptConfigById(storyBoardCreateCreate.getPrompt_id());

            // 调用 LLM 优化封面提示词
            String optimizedPrompt = llmUse.optimizeStoryImgPrompt(textModelConfig, promptConfig, storyBoardCreateCreate);

            result.put("success", true);
            result.put("optimizedPrompt", optimizedPrompt);

        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "优化异常：" + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 根据 prompt 生成图像，并保存到本地（统一路径）
     */
    @PostMapping("/image")
    public ResponseEntity<Map<String, Object>> generateImage(@RequestBody ImageCreate imageCreate) {

        Map<String, Object> result = new HashMap<>();

        try {
            // 获取模型配置
            ModelConfig imgModelConfig = modelConfigService.selectModelConfigById(imageCreate.getModelId());

            // 调用图像生成工具
            String imageUrl = imgUse.generateImage(imgModelConfig, imageCreate.getPrompt());

            // 统一保存并返回可访问URL
            String localUrl = saveGeneratedImage(imageUrl);

            result.put("success", true);
            result.put("prompt", imageCreate.getPrompt());
            result.put("imageUrl", imageUrl);
            result.put("localUrl", localUrl);

        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "生成异常：" + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 根据 prompt 生成图像，可接收最多三个参考图像
     */
    @PostMapping("/image-with-reference")
    public ResponseEntity<Map<String, Object>> generateImageWithReference(@RequestBody ImageCreate imageCreate) throws IOException {

        Map<String, Object> result = new HashMap<>();

        String imageUrl;
        try {
            //如何图片的开头是/dev-api 那么就去除这个
            String image = imageCreate.getImage();
            String image2 = imageCreate.getImage2();
            String image3 = imageCreate.getImage3();

            if (image != null && image.startsWith("/dev-api")) {
                image = image.replace("/dev-api", "");
            }
            if (image2 != null && image2.startsWith("/dev-api")) {
                image2 = image2.replace("/dev-api", "");
            }
            if (image3 != null && image3.startsWith("/dev-api")) {
                image3 = image3.replace("/dev-api", "");
            }
            ModelConfig imgModelConfig = modelConfigService.selectModelConfigById(imageCreate.getModelId());
            imageUrl = imgUse.generateImageWithReferences(imgModelConfig, imageCreate.getPrompt(), image, image2, image3);

            String localUrl = saveGeneratedImage(imageUrl);

            result.put("success", true);
            result.put("prompt", imageCreate.getPrompt());
            result.put("imageUrl", imageUrl);
            result.put("localUrl", localUrl);

        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "生成异常：" + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }

    /**
     * ✅ 保存生成的图片到 RuoYi 的统一目录
     * 支持 base64 或 http URL
     */
    @Autowired
    private ServerConfigs serverConfig;
    private String saveGeneratedImage(String imageUrl) throws IOException {
        String uploadPath = RuoYiConfig.getUploadPath(); // 比如 /home/ruoyi/uploadPath
        String datePath = DateUtils.datePath();           // yyyy/MM/dd
        String filename = IdUtils.fastSimpleUUID() + ".png";
        Path dir = Paths.get(uploadPath, datePath);
        Files.createDirectories(dir);

        Path filePath = dir.resolve(filename);

        if (imageUrl.startsWith("data:image/png;base64,")) {
            // Base64 -> 文件
            String base64Data = imageUrl.replace("data:image/png;base64,", "");
            byte[] bytes = Base64.getDecoder().decode(base64Data);
            Files.write(filePath, bytes, StandardOpenOption.CREATE);
        } else if (imageUrl.startsWith("http")) {
            // 下载 URL -> 文件
            FileUtils.copyURLToFile(new URL(imageUrl), filePath.toFile());
        } else {
            throw new IOException("无效的图像数据：" + imageUrl);
        }

        // 构建可访问 URL
        String relativePath = Constants.RESOURCE_PREFIX + "/upload/" + datePath + "/" + filename;
        String fullUrl = serverConfig.getUrl() + relativePath;

        System.out.println("✅ 图片已保存：" + filePath);
        System.out.println("🌐 访问URL：" + fullUrl);

        return relativePath;
    }
}
